import { defineComponent, reactive, onMounted, onUnmounted } from 'vue';
import Draw from './draw';

// 定义父组件
const ParentComponent = defineComponent({
  setup() {
    // 定义响应式数据对象 cdata，包含地区名称、计划贯通数据、已贯通数据和贯通率数据
    const cdata = reactive({
      category: [
        "市区",
        "万州",
        "江北",
        "南岸",
        "北碚",
        "綦南",
        "长寿",
        "永川",
        "璧山",
        "江津",
        "城口",
        "大足",
        "垫江",
        "丰都",
        "奉节",
        "合川",
        "江津区",
        "开州",
        "南川",
        "彭水",
        "黔江",
        "石柱",
        "铜梁",
        "潼南",
        "巫山",
        "巫溪",
        "武隆",
        "秀山",
        "酉阳",
        "云阳",
        "忠县",
        "川东",
        "检修"
      ],
      lineData: [
        18092,
        20728,
        24045,
        28348,
        32808,
        36097,
        39867,
        44715,
        48444,
        50415,
        56061,
        62677,
        59521,
        67560,
        18092,
        20728,
        24045,
        28348,
        32808,
        36097,
        39867,
        44715,
        48444,
        50415,
        36097,
        39867,
        44715,
        48444,
        50415,
        50061,
        32677,
        49521,
        32808
      ],
      barData: [
        4600,
        5000,
        5500,
        6500,
        7500,
        8500,
        9900,
        12500,
        14000,
        21500,
        23200,
        24450,
        25250,
        33300,
        4600,
        5000,
        5500,
        6500,
        7500,
        8500,
        9900,
        22500,
        14000,
        21500,
        8500,
        9900,
        12500,
        14000,
        21500,
        23200,
        24450,
        25250,
        7500
      ],
      rateData: []
    });

    // 计算贯通率数据的函数
    const setData = () => {
      cdata.rateData = [];
      for (let i = 0; i < cdata.barData.length; i++) {
        const rate = cdata.barData[i] / cdata.lineData[i];
        cdata.rateData.push(parseFloat(rate.toFixed(2)));
      }
    };

    // 随机更新数据的函数
    const updateDataRandomly = () => {
      cdata.lineData = cdata.lineData.map((val) => val + Math.floor(Math.random() * 5000)-2500);
      cdata.barData = cdata.barData.map((val) => val + Math.floor(Math.random() * 500) + 250);
      setData();
    };

    let intervalId: number | null = null;

    // 组件挂载时调用 setData 函数计算贯通率数据，并开启定时器
    onMounted(() => {
      setData();
      intervalId = setInterval(updateDataRandomly, 3000);
    });

    // 组件卸载时清除定时器
    onUnmounted(() => {
      if (intervalId) {
        clearInterval(intervalId);
      }
    });

    // 返回 JSX 元素，将 cdata 作为 props 传递给 Draw 组件
    return () => (
      <div>
        <Draw cdata={cdata} />
      </div>
    );
  }
});

export default ParentComponent;